<template>
  <div>
    <el-dialog
      title="添加商品"
      :visible.sync="localVisible"
      width="600px"
      @close="handleClose"
    >
      <el-form
        ref="productForm"
        :model="product"
        :rules="rules"
        label-width="100px"
      >
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="product.name" placeholder="请输入商品名称" />
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="product.description"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <!-- 商品类型 -->
        <el-form-item label="商品类型" prop="type">
          <el-input v-model="product.type" placeholder="请输入商品类型" />
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="product.price"
            :min="0"
            placeholder="请输入商品价格"
          />
        </el-form-item>

        <!-- 商品库存 -->
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="product.stock"
            :min="0"
            placeholder="请输入商品库存"
          />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="upload-demo"
            action="/api/adminhome/image"
            :show-file-list="false"
            :headers="uploadHeaders"
            :http-request="customUpload"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img
            v-if="product.image"
            :src="product.image"
            class="product-image-preview"
          />
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProductDialog',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      localVisible: this.visible,
      product: {
        name: '',
        description: '',
        type: '',
        image: '',
        price: 0,
        stock: 0,
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
        ],
        type: [{ required: true, message: '请输入商品类型', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
        image: [
          { required: true, message: '请上传商品图片', trigger: 'change' },
        ],
      },
    }
  },
  computed: {
    uploadHeaders() {
      const token = localStorage.getItem('jwtToken')
      return {
        Authorization: `Bearer ${token}`,
      }
    },
  },
  watch: {
    visible(val) {
      this.localVisible = val
    },
    localVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    handleClose() {
      this.resetForm()
      this.localVisible = false
    },
    resetForm() {
      this.$refs.productForm.resetFields()
      this.product = {
        name: '',
        description: '',
        type: '',
        image: '',
        price: 0,
        stock: 0,
      }
    },
    handleUploadSuccess(response) {
      console.log(response)
      if (response && response.data) {
        this.product.image = response.data
      }
    },
    // 上传前检查文件类型
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片格式!')
        return false
      }
      return true
    },
    async customUpload({ file, onSuccess, onError }) {
      try {
        // 重命名文件
        const timestamp = new Date().getTime()
        const extension = file.name.split('.').pop()
        const newFileName = `product_${timestamp}.${extension}`

        // 创建 FormData 对象并添加重命名后的文件
        const formData = new FormData()
        formData.append('file', file, newFileName)

        // 发起上传请求
        const response = await this.$http.post(
          '/api/adminhome/image',
          formData,
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('jwtToken')}`,
              'Content-Type': 'multipart/form-data',
            },
          }
        )

        onSuccess(response.data) // 处理成功回调
      } catch (error) {
        onError(error) // 处理失败回调
        this.$message.error('图片上传失败')
      }
    },
    closeDialog() {
      this.localVisible = false
    },
    submitForm() {
      this.$refs.productForm.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.product)
          this.localVisible = false
        } else {
          this.$message.error('请完善商品信息')
          return false
        }
      })
    },
  },
}
</script>

<style scoped>
.product-image-preview {
  width: 100px;
  height: 100px;
  margin-top: 10px;
}
</style>
